// import UIHelper from '../../Game/UIHelper';
import GameUtil from '../Util/GameUtil';
import SoundUtil from '../Util/SoundUtil';
import WebSocketClass from '../Util/WebSocketClass';
import TtUtil from '../Util/TtUtil';

let mBannerAd = null,
    mVideoAd = null,
    wxVideoId = null,
    wxBannerId = null;

export default class GameRecord {
    static GameManage = null;
    static recordTime = null;
    static recordStart : cc.Node = null;
    static recordStop : cc.Node  = null;
    static videoRes : string = '';
    static videoCallback: any;
    static shareCallback = null;
    static isRecord = false;
    static stopBack = null;
    static recordTimeMax = 300;

    static init(){
        this.initRecord();
        this.ttShareListener();
        this.ttOnShow();
    }
    static initRecord(){
        let self = this;
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            return;
        }
        this.GameManage = tt.getGameRecorderManager();
        this.GameManage.onStart(res => {
            Log("录屏开始");
            // do somethine;
            this.isRecord = true;
            this.videoRes = '';
            this.recordStart && (this.recordStart.active = false);
            this.recordStop && (this.recordStop.active = true);
            this.recordTime = new Date().getTime();
        });
        this.GameManage.onStop(res => {
            this.isRecord = false;
            if(this.recordTime){
                Log('还未开始,何来停止?');
                let currTime = new Date().getTime();
                let distance = currTime - this.recordTime;
                let second = distance/1000;
                if (Math.abs(second - this.recordTimeMax)<1){
                    Log('300秒自动停止,开启下一次录屏')
                    setTimeout(() => {
                        this.startRecord();
                    }, 1000);
                    return;
                }
            }
            this.recordStart && (this.recordStart.active = true);
            this.recordStop && (this.recordStop.active = false);

            let videoUrl = res.videoPath;
            this.videoRes = videoUrl;
            Log("录屏停止,临时地址:",res.videoPath);
            // do somethine;
            if (this.shareCallback){
                this.shareCallback();
                this.shareCallback = null;
            }
            if (this.stopBack){
                this.stopBack();
                this.stopBack = null;
            }
          });
        this.GameManage.onError(res =>{
            Log('录屏错误信息:',res)
        })
    }
    static refrestBtn(recordStart,recordStop){
        this.recordStart = recordStart;
        this.recordStop = recordStop;
        this.recordStart.active = !this.isRecord;
        this.recordStop.active = this.isRecord;
        Log('当前是否在录屏:',this.isRecord);
    }
    static startRecord(){
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            Log('浏览器平台,拒绝开始录屏')
            return;
        }
        if (this.isRecord){
            Log('当前正在录屏中')
            this.recordStart.active = !this.isRecord;
            this.recordStop.active = this.isRecord;
            return;
        }
        // this.recordStart && (this.recordStart.active = false);
        // this.recordStop && (this.recordStop.active = true);
        Log('开始录屏')
        this.GameManage.start({
            duration: this.recordTimeMax
        })
    }
    /**
     * 
     * @param isShare 是否自动调用分享
     * @param needClearPop 是否需要弹窗提示3秒时间
     * @param back 是否有回调函数,这个是自动分享后的奖励
     * @param stopBack 这个只有在FreeScene里才能调用,用于停止后拿到地址了出闯关成功失败
     */
    static stopRecord(isShare = true,needClearPop = true,back?,stopBack?){
        Log('停止录屏')
        if (back && stopBack){
            Log('传参错误!')
            return;
        }
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            Log('浏览器平台,拒绝停止录屏')
            return;
        }

        let currTime = new Date().getTime();
        let distance = currTime - this.recordTime;
        let second = distance/1000;
        if (!this.isRecord){
            Log('当前尚未开启录屏,我让他继续录着?')
            return;
        }

        if (second < 3){
            if (needClearPop){
                // UIHelper.addClearPop('录屏时间要大于3秒')
            }
            else{
                Log('录屏时间要大于三秒,但是因为不需要弹窗')
            }
        }
        else{
            this.recordTime = null;
            // this.recordStart && (this.recordStart.active = true);
            // this.recordStop && (this.recordStop.active = false);
            // if (second >= 25){
            //     this.GameManage.clipVideo({
            //         path: res.videoPath,
            //         timeRange: [25, 0],
            //         success(res) {
            //           Log(res.videoPath); // 生成最后10秒的视频
            //           videoUrl = res.videoPath;
            //         },
            //         fail(e) {
            //           Log('剪切视频失败',e);
            //         }
            //       })
            // }
            // back && (this.shareCallback = back);
            if (stopBack){
                this.stopBack = stopBack;
            }
            this.GameManage.stop();
            Log('调用自动停止接口')
            if (isShare){
                this.shareCallback = ()=>{
                    GameRecord.shareRecord(back);
                };
            }
        }
    }
    static shareRecord(back?){
        let self = this;
        if (this.videoRes == ''){
            return;
        }
        tt.shareAppMessage({
            channel: "video",
            title: "装扮小公主少女秀",
            desc: "绮丽世界少女梦，来和我比比穿搭能力吧!",
            imageUrl: "",
            templateId: "1ek3ab7akm0d9ir3kj", // 替换成通过审核的分享ID
            query: "",
            extra: {
              videoPath: this.videoRes, // 可替换成录屏得到的视频地址
              videoTopics: ["装扮", "童话"]
            },
            success() {
              Log("分享视频成功");
              if (back){
                back();
                self.videoRes = '';
              }
            },
            fail(e) {
              Log("分享视频失败");
            }
        });
    }
    /**
     * 
     * 查询是否授权
     * @param succ 
     * @param fail 
     * @example
     *  let result = await TtUtil.selectEmpower();
        if (result){
            TtUtil.getUserInfo(
                (res)=>{
                    UserData.ttNickName = res.userInfo.nickName;
                    UserData.ttHeadImg = res.userInfo.avatarUrl;
                    self.chatServerLogin();
                },
                ()=>{
                    // UIHelper.addClearPop('点击授权个人信息',()=>{
                    //     TtUtil.getAuthorize((res)=>{
                    //         UserData.ttNickName = res.userInfo.nickName;
                    //         UserData.ttHeadImg = res.userInfo.avatarUrl;
                    //         self.chatServerLogin();
                    //     });
                    // })
                    self.loginSucc();
                })
        }
        else{
            // UIHelper.addClearPop('点击授权个人信息',()=>{
            //     TtUtil.getAuthorize((res)=>{
            //         UserData.ttNickName = res.userInfo.nickName;
            //         UserData.ttHeadImg = res.userInfo.avatarUrl;
            //         self.chatServerLogin();
            //     });
            // })
            self.loginSucc();
        }
     */
    static async checkEmpower(succ,fail){
        let result = await TtUtil.selectEmpower();
        if (result){
            TtUtil.getUserInfo(
                (res)=>{
                    //UserData.ttNickName = res.userInfo.nickName;
                    //UserData.ttHeadImg = res.userInfo.avatarUrl;
                    succ(res.userInfo);
                },
                ()=>{
                    fail();
                })
        }
        else{
            fail();
        }
    }
    static ttShareListener () {
        //shareImg
        if (cc.sys.platform == cc.sys.WECHAT_GAME) {
            tt.onShareAppMessage(function (res) {
                return {
                    title: '装扮小公主少女秀',
                    desc: '绮丽世界少女梦，来和我比比审美能力吧!',
                    path: '/pages/index/index?from=sharebuttonabc&otherkey=othervalue', 
                    imageUrl:'',    //cc.url.raw("resources/Texture/share1.png")本地写法
                    templateId:'1ek3ab7akm0d9ir3kj',        //这个填过审的分享id  其实上面的都没啥用 主要是这个
                    success () {
                      Log('转发发布器已调起，并不意味着用户转发成功，微头条不提供这个时机的回调');
                    },
                    fail () {
                      Log('转发发布器调起失败');
                    }
                }
            });
        }
    }
    static ttOnShow(){
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            return;
        }
        Log('重新回来 此时握有几个ws?',WebSocketClass.wsArray.length)
        tt.onShow((query,referrerInfo)=>{
            for(let ws of WebSocketClass.wsArray){
                ws.sendSocketMessage('0')
            }
        })
    }
    static initVideo(videoId?,bannerId?) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            Log('浏览器平台,拒绝视频')
            return;
        }
        wxBannerId = bannerId?bannerId:GameUtil.wxBannerId;
        wxVideoId = videoId ? videoId : GameUtil.wxVideoId;

        let screenSize = wx.getSystemInfoSync();

        if (!wx.createRewardedVideoAd){
            Log('尚未注册广告api')
            return;
        }

        mVideoAd = wx.createRewardedVideoAd({
            adUnitId: wxVideoId
        })
        mVideoAd.onError((errMsg, errCode) => {
            Log('错误信息:', errMsg);
            Log('错误代码:', errCode);
            if (this.videoCallback){
                mVideoAd.offClose(this.videoCallback);
            }
            this.videoCallback = null;
        })
    }
            /**
     * 播放banner
     */
    static showBanner(vh) {

        if (mBannerAd) {
            mBannerAd.destory();
        }

        mBannerAd = wx.createBannerAd({
            adUnitId: wxBannerId,
            style: {
                left: 0,
                top: 0,
                width: 300,
                height : 100
            }
        });

        var self = this;
        mBannerAd.onResize(res => {
            mBannerAd.show();
        });

    }

    static hideBanner(){
        if (mBannerAd) {
            mBannerAd.destory();
        }
    }

    static showVideo(callback?) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME){
            Log('浏览器平台,拒绝开始录屏')
            callback && callback(true);
            return;
        }
        if (!mVideoAd) {
            mVideoAd = wx.createRewardedVideoAd({
                adUnitId: wxVideoId
            })
            // ShareHelper.startShare(callback,'InviteFriend',null);

        }
        mVideoAd.load()
            .then(() => mVideoAd.show())
            .catch(err => Log(err.errMsg))

        var thisCallback = function (res) {
            if (callback) {
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    callback(true);
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    callback(false);
                }
            }
            SoundUtil.resumeMusic();
            mVideoAd.offClose(thisCallback);
            mVideoAd.onError((errMsg, errCode) => {
                
            });
        };

        mVideoAd.onClose(thisCallback);
    }
}

